<?php
function UHU_output($doc,$lifetime=null,$last_mod=null)
{
	$lifetime = isset($lifetime) ? $lifetime : 300;
	$doc = (string)$doc;
	$ETag = sha1($doc);
	if(strlen($doc) > 0)
	{
		if(UHU_server::getInstance()->gzip())
		{
			$gzipped = gzencode($doc,constant('UHU_server::GZIP_COMPRESSION_LEVEL'));
			if(strlen($gzipped) < strlen($doc))
			{
				$doc = $gzipped;
				unset($gzipped);
				header('Content-Encoding:gzip');
			}
		}
	}
	header('Last-Modified:' . gmdate('r',$_SERVER['REQUEST_TIME']));
	header('Expires:' . gmdate('r',$_SERVER['REQUEST_TIME'] + $lifetime));
	header(sprintf('Cache-Control: max-age=%1$u, s-maxage=%1$u, public, must-revalidate, proxy-revalidate',$lifetime));
	header('ETag:' . $ETag);
	if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $ETag)
	{
		header('HTTP/1.1 304 Not Modified');
		exit;
	}
	else if(isset($last_mod,$_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_mod <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
	{
		header('HTTP/1.1 304 Not Modified');
		exit;
	}
	else if(strlen($doc) === 0)
	{
		header('HTTP/1.1 204 No Content');
		exit;
	}
	else
	{
		header('Content-Length:' . strlen($doc));
		die($doc);
	}
}
function UHU_callback_cache_output($filename,$callback,$lifetime=null)
{
	$lifetime = isset($lifetime) ? $lifetime : 300;
	if(defined('UHU_CACHE') === false)
	{
		throw new RuntimeException('Cache directory not set, cannot cache document.');
	}
	else
	{
		if(substr($filename,0,1) != '/')
		{
			$filename = '/' . $filename;
		}
		$filename = UHU_CACHE . $filename;
		if(
			file_exists($filename) === false ||
			(filemtime($filename) + $lifetime) < $_SERVER['REQUEST_TIME']
		){
			if(file_put_contents($filename,call_user_func($callback)) === false)
			{
				throw new RuntimeException('Could not cache document in file system.');
			}
		}
		if(($last_mod = filemtime($filename)) === false)
		{
			throw new RuntimeException('Could not fetch last mod time for document.');
		}
		else
		{
			UHU_output(file_get_contents($filename),$lifetime,$last_mod);
		}
	}
}
?>